<template>
  <view>
    <loading v-if="0 != loading" :status="loading" />
    <view class="page-container" v-else>
      <view class="order-type-container">
          <view class="order-type-select" :style="'padding-top:' + menuBtnInfo.top + 'px;'">
          <image class="icon-arrow-left" src="/static/image/arrow_left.png" @tap="back"></image>
          <view class="select-content" @tap="showSelectFun">
            <view class="select-title">门店券订单</view>
            <image class="select-btn" :src="'/static/image/merchant/' + (showSelect ? 'arrow_down.png' : 'arrow_up.png')">
            </image>
          </view>
        </view>
        <view class="select-holder"></view>
        
        <u-popup :show="showSelect" mode="top" @close="onClose">
          <view class="select-section" :style="'margin-top:' + popupMt + 'rpx'">
            <block v-for="(item, index) in selectList" :key="index">
              <view :class="'select-item ' + (selectIndex == index ? 'selected' : '')" :data-index="index"
                :data-item="item" @tap="changeType">
                <text>{{ item.name }}</text>
                <image class="ic_selected" v-if="selectIndex == index" src="/static/image/ic_selected.png"></image>
              </view>
            </block>
          </view>
        </u-popup>

        <!-- tabbar start -->
        <view class="tabBar-container" v-if="isLogin">
          <block v-for="(item, index) in tabBar" :key="item.id">
            <view :class="'tabBar-item ' + (item.isActive ? 'active' : '')" @tap="changeActive" :data-id="item.id">
              <text>{{ item.name }}</text>
              <view class="active-tag" v-if="index == activeIndex"
                :style="'background-color: ' + platformConfig.baseColor + ';'"></view>
            </view>
          </block>
        </view>
        <!-- tabbar end -->
      </view>

      <!-- content-container -->
      <view class="content-container" >
        <!-- 全部 -->
        <view style="width: 100%;height: 210rpx;"></view>
        <view v-if="tabBar[0].isActive" class="content-item">
          <view class="coupon-order-item" :data-order="couponOrder" @tap.stop.prevent="toOrderDetail"
            v-for="(couponOrder, index) in couponOrderList[activeIndex]" :key="couponOrder.payId">
            <view class="content-item-time">
              <view>订单编号{{ couponOrder.payId }}</view>
              <view class="content-item-toPay">
                <coupon-order-status :couponOrder="couponOrder"></coupon-order-status>
                <view class="img-arrow">
                  <image src="/static/image/arrow_right.png"></image>
                </view>
              </view>
            </view>

            <coupon-order :showOrderType="showOrderType" :couponOrder="couponOrder"></coupon-order>
          </view>
        </view>
        <!-- 待付款 -->
        <view v-if="tabBar[1].isActive" class="content-item">
          <view class="coupon-order-item" :data-order="couponOrder" @tap.stop.prevent="toOrderDetail"
            v-for="(couponOrder, index) in couponOrderList[activeIndex]" :key="couponOrder.payId">
            <view class="content-item-time">
              <view>订单编号{{ couponOrder.payId }}</view>
              <view class="content-item-toPay">
                <coupon-order-status :couponOrder="couponOrder"></coupon-order-status>
                <view class="img-arrow">
                  <image src="/static/image/arrow_right.png"></image>
                </view>
              </view>
            </view>

            <coupon-order :showOrderType="showOrderType" :couponOrder="couponOrder"></coupon-order>
          </view>
        </view>
        <!-- 已付款 -->
        <view v-if="tabBar[2].isActive" class="content-item">
          <view class="coupon-order-item" :data-order="couponOrder" @tap.stop.prevent="toOrderDetail"
            v-for="(couponOrder, index) in couponOrderList[activeIndex]" :key="couponOrder.payId">
            <view class="content-item-time">
              <view>订单编号{{ couponOrder.payId }}</view>
              <view class="content-item-toPay">
                <coupon-order-status :couponOrder="couponOrder"></coupon-order-status>
                <view class="img-arrow">
                  <image src="/static/image/arrow_right.png"></image>
                </view>
              </view>
            </view>

            <coupon-order :showOrderType="showOrderType" :couponOrder="couponOrder"></coupon-order>
          </view>
        </view>
        <!-- 退款 -->
        <view v-if="tabBar[3].isActive" class="content-item">
          <view class="coupon-order-item" :data-order="couponOrder" @tap.stop.prevent="toOrderDetail"
            v-for="(couponOrder, index) in couponOrderList[activeIndex]" :key="couponOrder.payId">
            <view class="content-item-time">
              <view>订单编号{{ couponOrder.payId }}</view>
              <view class="content-item-toPay">
                <coupon-order-status :couponOrder="couponOrder"></coupon-order-status>
                <view class="img-arrow">
                  <image src="/static/image/arrow_right.png"></image>
                </view>
              </view>
            </view>

            <coupon-order :showOrderType="showOrderType" :couponOrder="couponOrder"></coupon-order>
          </view>
        </view>
        <view v-if="!couponOrderList[activeIndex] || couponOrderList[activeIndex].length == 0" class="empty-container">
          <image class="empty-img" src="/static/image/home_ic_empty@2x.png"></image>
          <view>暂无相关记录</view>
        </view>
      </view>
      <view class="noMoreOrder" v-if="!haveMoreArr[activeIndex] && couponOrderList[activeIndex].length > 0">没有更多相关订单了
      </view>
      <!-- 返回主页按钮 -->
      <gohome id="gohome"></gohome>
    </view>
  </view>
</template>
<script>
  import {
    http
  } from '@/utils/commonRequest.js'; // 局部引入
  import gohome from '@/components/gohome/gohome';
  import couponOrderStatus from '@/components/couponOrderStatus/couponOrderStatus.vue'
  import couponOrder from '@/components/couponOrder/couponOrder.vue'
  // import vanPopup from '@vant/weapp/popup/index';
  import loading from '@/components/loading/loading';
  const app = getApp();

  const utils = require('../../../utils/util.js'); //初始化请求分页参数

  const initQueryParams = [{
      couponOrderStatus: '',
      page: 1,
      limit: 10
    },
    {
      couponOrderStatus: 1,
      page: 1,
      limit: 10
    },
    {
      couponOrderStatus: 2,
      page: 1,
      limit: 10
    },
    {
      couponOrderStatus: 3,
      page: 1,
      limit: 10
    }
  ];
  export default {
    components: {
      gohome,
      couponOrderStatus,
      couponOrder,
      // vanPopup,
      loading
    },
    //下拉临时数据存放
    data() {
      return {
        //优惠券订单列表请求参数
        params: JSON.parse(JSON.stringify(initQueryParams)),
        tempdata: [],
        isLogin: false,
        //是否登录
        loading: 1,
        //加载中
        showOrderType: true,
        //是否显示订单类型标签
        platformConfig: app.globalData.platformConfig,
        //tabbar
        tabBar: [{
            id: 0,
            name: '全部',
            isActive: true
          },
          {
            id: 1,
            name: '待付款',
            isActive: false
          },
          {
            id: 2,
            name: '已付款',
            isActive: false
          },
          {
            id: 3,
            name: '已退款',
            isActive: false
          }
        ],
        activeIndex: 0,
        //当前选中的tab
        couponTypeIndex: 1,
        couponOrderList: [],
        //优惠券列表数据
        haveMoreArr: [true, true, true, true],
        orderType: 1,
        //订单类型 1：普通订单，2：秒杀订单，3抽奖活动订单, 6：拼团订单
        showSelect: false,
        selectIndex: 2,
        selectList: [{
            name: '商城订单',
            path: '/subPackages/orderPkg/pages/orderList/orderList'
          },
          {
            name: '电子卡券订单',
            path: '/subPackages/right/pages/myProfitsOrder/myProfitsOrder'
          },
          // {
          //   name: '门店券订单',
          //   path: '/pages/coupon/myCouponOrder/myCouponOrder'
          // }
        ],
        menuBtnInfo: null,
        popupMt: '',
        goodsListMt: '',
        isActive: '',
        couponOrder: {
          payId: '',
          status: '',
          coupon: {
            couponType: '',
            discountAmt: ''
          },
          orderType: 0,
          couponName: '',
          exchangeRuleType: 0,
          point: '',
          couponId: '',
          saleRuleId: '',
          sid: ''
        }
      };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
      // #ifdef MP-WEIXIN
      this.menuBtnInfo = wx.getMenuButtonBoundingClientRect()
      this.popupMt = (this.menuBtnInfo.height + this.menuBtnInfo.top) * 2;
      // #endif
      const that = this;
      // let menuBtnInfo = uni.getMenuButtonBoundingClientRect();
      // console.log(menuBtnInfo);
      // let popupMt = (menuBtnInfo.height + menuBtnInfo.top) * 2;
      // this.menuBtnInfo = menuBtnInfo
      // this.popupMt = popupMt
      this.platformConfig = app.globalData.platformConfig
      this.showOrderType = that.showOrderType //登录之后才查询订单列表，减少请求
			if (!utils.isEmpty(options.typeId)) {
			  that.activeIndex = options.typeId;
			}
      this.$checkLogin().then((res) => {
        // if (res == 'authed') {
        this.isLogin = true
        this.getCouponOrderList();
        // }
      });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
      let needRefresh = uni.getStorageSync('ZSNSH_ORDER_REFRESH');

      if (needRefresh) {
        this.onPullDownRefresh();
        uni.setStorageSync('ZSNSH_ORDER_REFRESH', false);
      }

      this.$checkLogin().then((res) => {
        // if (res == 'authed') {
        this.isLogin = true
        // }
      });
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
      let index = this.activeIndex;

      if (!this.haveMoreArr[index]) {
        return;
      } else {
        this.getCouponOrderList();
      }
    },
    /**
     * 页面下拉刷新
     */
    onPullDownRefresh() {
      //页面下拉刷新时，将分页查询参数初始化
      this.haveMoreArr = [true, true, true, true]
      this.params = JSON.parse(JSON.stringify(initQueryParams));
      this.tempdata = [];
      this.isRefresh = true; //标记为该次请求为刷新列表，为true时请求结束后调用wx.stopPullDownRefresh()

      this.getCouponOrderList();
    },
    methods: {
      formatFenMoney(s) {
        if (undefined == s || '' == s || null == s) {
          return 0;
        } else {
          return (s / 100)
        }
      },
      formatFenMoney(s) {
        if (undefined == s || '' == s || null == s) {
          return 0;
        } else {
          return (s / 100)
        }
      },
     

      /** 切换显示 */
      changeActive: function(e) {
        let index = e.currentTarget.dataset.id;
        let tabbar = this.tabBar;

        if (index == this.activeIndex) {
          return;
        }
        tabbar.map((v) => {
          v.isActive = false;
        });
        tabbar[index].isActive = true;
        this.tabBar = tabbar
        this.activeIndex = index

        if (this.isLogin) {
          this.getCouponOrderList();
        }
      },

      /** 切换订单类型 */
      changeType: function(e) {
        let index = e.currentTarget.dataset.index;
        let item = e.currentTarget.dataset.item; // console.log(e.currentTarget.dataset);
        // console.log(this.data.couponTypeIndex);

        if (index != this.couponTypeIndex) {
          this.selectIndex = index
          uni.redirectTo({
            url: item.path
          });
        } else {
          this.onClose();
        }
      },

      /** 显示筛选框 */
      showSelectFun: function() {
        let that = this;
        that.showSelect = !that.showSelect
      },

      /** 关闭弹窗 */
      onClose: function() {
        let that = this;
        that.showSelect = false
      },

      back: function() {
        uni.navigateBack({
          delta: 1
        });
      },

      getRect: function() {
        let that = this;
        let query = uni.createSelectorQuery();
        query
          .selectAll('.order-type-container')
          .boundingClientRect((res) => {
            console.log(res);
            let goodsListMt = (res[0] && res[0].height ? res[0].height : 0) + 5;
            console.log(goodsListMt);
            that.goodsListMt = goodsListMt
          })
          .exec();
      },

      /** 获取优惠券订单列表 */
      getCouponOrderList: function() {
        let that = this;
        let index = that.activeIndex;
        let haveMoreArr = that.haveMoreArr;
        console.log(haveMoreArr);

        if (!haveMoreArr[index]) {
          console.log('index:%d没有更多了', index);
          return;
        }

        let queryParams = that.params[index];
        let orderList = that.tempdata[index] ? that.tempdata[index] : [];
        console.log(queryParams);
        http.get('zsnshCoupon/myCouponOrderList', {
            params: queryParams
          })
          .then((res) => {
            console.log(res);

            if (res.data.code == '200') {
              haveMoreArr[index] = res.data.haveMore;
              that.tempdata[index] = [...orderList, ...res.data.couponOrderList];
              queryParams.page++;
              that.params[index] = queryParams;
              that.couponOrderList = [].concat(that.tempdata)
              that.haveMoreArr = haveMoreArr
              that.loading = 0
              that.getRect();
            } else {
              utils.message(res.data.msg);
            }

            if (that.isRefresh) {
              uni.stopPullDownRefresh();
              that.isRefresh = false;
            }
          })
          .catch((err) => {
            if (that.isRefresh) {
              uni.stopPullDownRefresh();
              that.isRefresh = false;
            }
          });
      },

      toOrderDetail: function(e) {
        let couponOrder = e.currentTarget.dataset.order;
        console.log(couponOrder);
        let payId = couponOrder.payId;
        let orderType = couponOrder.orderType;
        let // orderId = couponOrder.sid,
          groupbuyStatus = couponOrder.groupbuyStatus;
        let payStatus = couponOrder.payStatus;
        console.log();

        if (6 == orderType && 2 == payStatus && 0 == groupbuyStatus) {
          //拼团类型且状态为已支付
          uni.navigateTo({
            url: '/couponMarketingPkg/pages/couponGroupBuy/groupbuyOrderDetail/groupbuyOrderDetail?payId=' + payId
          });
        } else {
          uni.navigateTo({
            url: '/pages/coupon/myCouponDetail/myCouponDetail?payId=' + payId
          });
        }
      },

      addToCart() {
        console.log('占位：函数 addToCart 未声明');
      }
    }
  };
</script>
<style>
  @import '@/templates/zsnshTemplates.css';

  page {
    background-color: #fff;
  }

  .page-container {
    /* padding-top: 280rpx; */
  }

  .order-type-container {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 200;
    background-color: #fff;
  }

  .order-type-select {
    /* height: 80rpx; */
    position: relative;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    /* margin-bottom: 12rpx; */
    background-color: #fff;
    z-index: 99999;
  }

  .select-content {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    color: #000;
    font-size: 34rpx;
    font-weight: 500;
  }

  .icon-arrow-left {
    width: 36rpx;
    height: 36rpx;
    position: absolute;
    left: 30rpx;
  }

  .select-btn {
    width: 24rpx;
    height: 24rpx;
    margin-left: 14rpx;
  }

  .select-holder {
    width: 100%;
    height: 12rpx;
    background-color: #fff;
  }

  .select-section {
    margin-top: 80rpx;
    padding: 24rpx 24rpx 0;
    display: flex;
    /* justify-content: space-between; */
		justify-content: space-around;
    flex-wrap: wrap;
    border-top: 1px solid rgba(0, 0, 0, 0.06);
  }

  .select-item {
    width: 218rpx;
    height: 72rpx;
    border-radius: 8rpx;
    background: #f5f5f5;
    text-align: center;
    line-height: 72rpx;
    font-size: 28rpx;
    font-weight: 400;
    color: #333;
    position: relative;
    margin-bottom: 24rpx;
  }

  .selected {
    background: #ffebeb;
    color: #ff6464;
  }

  .ic_selected {
    width: 39rpx;
    height: 36rpx;
    position: absolute;
    bottom: 0;
    right: 0;
  }

  .type-switch {
    width: 100%;
    height: 100rpx;
    background-color: #fff;
  }

  .tabBar-container {
    display: flex;
    justify-content: space-around;
    height: 118rpx;
    box-sizing: border-box;
    background-color: #fff;
    width: 100%;
    border-top: 1px solid #eee;
    box-shadow: 0px 20rpx 60rpx 0px rgba(112, 136, 210, 0.1);
  }

  .tabBar-item {
    line-height: 44rpx;
    font-size: 32rpx;
    color: #666;
    margin-top: 50rpx;
    padding-bottom: 50rpx;
  }

  .active-tag {
    width: 100%;
    height: 8rpx;
    border-radius: 4rpx;
  }

  .content-container {}

  .content-item {
    position: relative;
    margin: 54rpx 24rpx 24rpx;
  }

  .coupon-order-item {
    width: 100%;
    margin-bottom: 24rpx;
    background-color: #fff;
    border-radius: 24rpx;
    padding-top: 30rpx;
    box-shadow: 0rpx 20rpx 60rpx 0rpx rgba(112, 136, 210, 0.1);
  }

  .content-item-time {
    color: #999;
    font-size: 24rpx;
    display: flex;
    justify-content: space-between;
    padding: 0 24rpx;
  }

  .content-item-toPay {
    font-size: 28rpx;
    color: #999;
    line-height: 38rpx;
    float: right;
  }

  .img-arrow {
    width: 24rpx;
    height: 38rpx;
    line-height: 38rpx;
    display: inline-block;
    margin-left: 8rpx;
  }

  .img-arrow image {
    width: 24rpx;
    height: 24rpx;
  }

  .content-item-order {
    display: flex;
    justify-content: space-between;
    padding: 32rpx 24rpx;
  }

  .item-order-img {
    flex-shrink: 0;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 112rpx;
    height: 112rpx;
  }

  .item-order-img image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }

  .discount-info {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding-right: 10rpx;
    width: 120rpx;
    line-height: 1;
    color: #fff;
    letter-spacing: -1px;
  }

  .icon-price {
    font-size: 20rpx;
  }

  .icon-discount {
    font-size: 26rpx;
    font-weight: bold;
  }

  .order-money {
    position: absolute;
    top: 50%;
    left: 50%;
  }

  .item-order-info {
    flex: 1;
    margin-left: 24rpx;
  }

  .info-title {
    display: flex;
    align-items: center;
  }

  .info-title-name {
    width: 450rpx;
    font-size: 30rpx;
    color: #222;
    font-weight: bold;
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .info-point {
    font-size: 24rpx;
    color: #999;
    margin-top: 16rpx;
    display: flex;
    justify-content: space-between;
  }

  .line {
    width: 100%;
    height: 1rpx;
    background-color: #eaeaea;
    margin-top: 32rpx;
  }

  .content-amount {
    width: 100%;
    height: 102rpx;
    text-align: right;
    line-height: 102rpx;
    border-top: 1px solid #eaeaea;
    padding: 0 24rpx;
  }

  .amount-count {
    font-size: 24rpx;
    color: #999;
  }

  .count-num {
    color: #000;
    font-size: 26rpx;
  }

  .amount-point {
    font-size: 26rpx;
    color: #000;
    font-weight: bolder;
  }

  .icon-RMB {
    font-size: 20rpx;
  }

  .icon-RMB text {
    color: #000;
    font-size: 26rpx;
    font-weight: bolder;
  }

  .noMoreOrder {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    text-align: center;
    color: #ccc;
    margin-top: 38rpx;
    margin-bottom: 48rpx;
  }

  .noMoreOrder::before,
  .noMoreOrder::after {
    position: relative;
    content: '';
    width: 54rpx;
    height: 2rpx;
    background-color: rgba(0, 0, 0, 0.06);
  }

  .noMoreOrder::before {
    margin-right: 20rpx;
  }

  .noMoreOrder::after {
    margin-left: 20rpx;
  }

  /* 空列表 */
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 26rpx;
    color: #999;
    padding-top: 200rpx;
  }

  .empty-img {
    width: 644rpx;
    height: 310rpx;
  }
</style>
